from flask import Blueprint, jsonify, request
from flask_mysqldb import MySQL
from config.config import MysqlConfig  # 需要创建配置文件
from functools import wraps

# 定义mysql蓝图，这里mysql并不似接口前缀，只是名字
mysql_bp = Blueprint('mysql', __name__)

# 初始化MySQL
mysql = MySQL()

# 如果采用蓝图调用，入参app是Flask对象，这里用初始化，所以入参改state
def init_mysql(state):
    app = state.app
    app.config['MYSQL_HOST'] = MysqlConfig.MYSQL_HOST
    app.config['MYSQL_USER'] = MysqlConfig.MYSQL_USER
    app.config['MYSQL_PASSWORD'] = MysqlConfig.MYSQL_PASSWORD
    app.config['MYSQL_DB'] = MysqlConfig.MYSQL_DB
    print(f"MYSQL_HOST: {app.config['MYSQL_HOST']}" )
    print(f"MYSQL_USER: {app.config['MYSQL_USER']}")
    print(f"MYSQL_PASSWORD: {app.config['MYSQL_PASSWORD']}")
    print(f"MYSQL_DB: {app.config['MYSQL_DB']}")   
    mysql.init_app(app)

# 注册初始化函数
mysql_bp.record(init_mysql)

# 统一接口异常处理
def handle_db_exceptions(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        try:
            return f(*args, **kwargs)
        except Exception as e:
            return jsonify({'status': 'error', 'message': str(e)})
    return decorated_function

# 这里没有使用@handle_db_exceptions装饰器，里面采用try catch
@mysql_bp.route('/getAreaInfoList', methods=['GET'])
def get_area_info_list():
    try:
        cur = mysql.connection.cursor()
        cur.execute("SELECT * FROM area_info")
        data = cur.fetchall()
        cur.close()
        
        # 将结果转换为字典列表
        area_list = []
        for row in data:
            area_list.append({
                'addr_code': row[0],
                'addr_name': row[1]
            })
        
        return jsonify({'status': 'success', 'data': area_list})
    except Exception as e:
        return jsonify({'status': 'error', 'message': str(e)})

# 添加区域信息
@mysql_bp.route('/addAreaInfo', methods=['POST'])
@handle_db_exceptions
def add_area_info():
    data = request.get_json()
    code = data.get('code')
    name = data.get('name')
    
    cur = mysql.connection.cursor()
    cur.execute("INSERT INTO area_info (addr_code,addr_name) VALUES (%s,%s)", (code,name))
    mysql.connection.commit()
    cur.close()
    
    return jsonify({'status': 'success', 'message': '添加成功'})

# 更新区域信息
@mysql_bp.route('/updateAreaInfo/<string:code>', methods=['PUT'])
@handle_db_exceptions
def update_area_info(code):
    data = request.get_json()
    code = data.get('code')
    name = data.get('name')
    
    cur = mysql.connection.cursor()
    cur.execute("UPDATE area_info SET addr_name = %s WHERE addr_code = %s", (name, code))
    mysql.connection.commit()
    cur.close()
        
    return jsonify({'status': 'success', 'message': '更新成功'})

# 删除区域信息
@mysql_bp.route('/deleteAreaInfo/<string:code>', methods=['DELETE'])
@handle_db_exceptions
def delete_area_info(code):
    cur = mysql.connection.cursor()
    cur.execute("DELETE FROM area_info WHERE addr_code = %s", (code))
    mysql.connection.commit()
    cur.close()
        
    return jsonify({'status': 'success', 'message': '删除成功'})
